package src.main.java.org.reflect.obtainClassConstructor;

import org.junit.Test;

import java.lang.reflect.Constructor;

public class TestConstructor {
    @Test
    public void testGetConstructors() throws NoSuchMethodException {
        //1.得到类的class对象
        Class catClass = Cat.class;
        //获取类的全部构造器
        Constructor[] constructors = catClass.getConstructors(); //只能获取public修饰的构造器
        for (Constructor constructor : constructors) {
            System.out.println(constructor.getName()+"--->"+constructor.getParameterCount());
        }

        Constructor declaredConstructor = catClass.getDeclaredConstructor(); //获取所有的构造器

    }

    @Test
    public void testGetConstructor() throws Exception {
        Class catClass = Cat.class;
        //获取某个构造器
       // Constructor constructor = catClass.getConstructor(); //获取无参的public构造器
        Constructor declaredConstructor = catClass.getDeclaredConstructor(); //获取无参的所有的构造器

        Constructor constructor1 = catClass.getConstructor(String.class, String.class);//获取有参的public有参构造器
        Constructor declaredConstructor1 = catClass.getDeclaredConstructor(String.class, String.class);

        declaredConstructor.setAccessible(true); //禁止检查访问权限
        Cat cat = (Cat) declaredConstructor.newInstance();//调用无参构造器,

        declaredConstructor1.setAccessible(true);
        Cat o = (Cat)declaredConstructor1.newInstance("叮当猫", "花色");
    }
}
